package com.xiaowei.gym.gymjsp.ware.servlet;
import com.google.gson.Gson;
import com.xiaowei.gym.gymjsp.ware.dao.GymMenuDao;
import com.xiaowei.gym.gymjsp.ware.dao.impl.GymMenuDaoImpl;
import com.xiaowei.gym.gymjsp.ware.entity.GymMenuEntity;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/gym/menu")
public class GymMenuServlet extends HttpServlet {

    private GymMenuDao gymMenuDao;

    @Override
    public void init() {
        gymMenuDao = new GymMenuDaoImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<GymMenuEntity> menuList = gymMenuDao.getAllMenus();
        System.out.println("从数据库查询到的menuList:"+menuList);
        System.out.println("menuList"+menuList);
        String json = new Gson().toJson(menuList); // 将菜单数据转换为 JSON 格式
        System.out.println(menuList);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json); // 返回 JSON 数据
        menuList.clear();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }


    @Override
    public void destroy() {
        super.destroy();
    }
}
